#include "prescriptionchecker.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QWebEngineView>
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QApplication>
#include <QDebug>
#include <QUrl>
#include <QTimer>
#include <QDateTime>
#include <QWebEngineProfile>
#include <QWebChannel>
#include <QWebEnginePage>
#include <QRandomGenerator>
#include <QTime>
#include <QSettings>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QDesktopServices>

PrescriptionChecker::PrescriptionChecker(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_currentReply(nullptr)
    , m_apiEndpoint("https://ds-api.yaodaotec.com/doctor/presc/sendCheck")
    , m_webPageUrl("http://ds.yaodaotec.com/views/csCheckResultPage.html")  // 默认值
    , m_dialogWidth(1032)   // 默认宽度
    , m_dialogHeight(580)   // 默认高度
    , m_currentDialog(nullptr)
    , m_webChannel(new QWebChannel(this))
{
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &PrescriptionChecker::onNetworkReplyFinished);
    
    // 从配置文件读取URL和弹窗大小
    QString configPath = QCoreApplication::applicationDirPath() + "/config.ini";
    QFileInfo fileInfo(configPath);
    
    if (fileInfo.exists()) {
        QSettings settings(configPath, QSettings::IniFormat);
        
        // 读取URL
        QString url = settings.value("url", "").toString();
        if (!url.isEmpty()) {
            m_webPageUrl = url;
            qDebug() << "从配置文件加载URL:" << m_webPageUrl;
        } else {
            qDebug() << "配置文件中未找到URL，使用默认值:" << m_webPageUrl;
        }
        
        // 读取弹窗宽度
        int width = settings.value("dialog_width", 0).toInt();
        if (width > 0) {
            m_dialogWidth = width;
            qDebug() << "从配置文件加载弹窗宽度:" << m_dialogWidth;
        } else {
            qDebug() << "配置文件中未找到弹窗宽度，使用默认值:" << m_dialogWidth;
        }
        
        // 读取弹窗高度
        int height = settings.value("dialog_height", 0).toInt();
        if (height > 0) {
            m_dialogHeight = height;
            qDebug() << "从配置文件加载弹窗高度:" << m_dialogHeight;
        } else {
            qDebug() << "配置文件中未找到弹窗高度，使用默认值:" << m_dialogHeight;
        }
    } else {
        qDebug() << "配置文件不存在，使用默认值 - URL:" << m_webPageUrl 
                 << "宽度:" << m_dialogWidth << "高度:" << m_dialogHeight;
    }
}

PrescriptionChecker::~PrescriptionChecker()
{
    if (m_currentReply) {
        m_currentReply->deleteLater();
    }
}

void PrescriptionChecker::DoctorCheck(int tag, const QString& xmlData, DataCallbackFunction dataCallback)
{
    if (m_currentReply) {
        m_currentReply->abort();
        m_currentReply->deleteLater();
    }
    
    if (dataCallback) {
        m_dataCallback = dataCallback;
    }
    m_xmlData = xmlData;
    
    QUrl url(m_apiEndpoint + "?xml=" + xmlData + "&tag=" + QString::number(tag));
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    
    m_currentReply = m_networkManager->post(request, "");
}

void PrescriptionChecker::CheckProbleNotify(const QString& data)
{
    qDebug() << "CheckProbleNotify:" << data;
    
    // 关闭当前显示的Web页面对话框
    if (m_currentDialog) {
        qDebug() << "关闭当前对话框";
        m_currentDialog->close();
        m_currentDialog->deleteLater();
        m_currentDialog = nullptr;
    }
    
    if (data == "0") {
        DoctorCheck(2, m_xmlData);
    }
    m_dataCallback(data.toUtf8().constData());
}

void PrescriptionChecker::OpenUrl(const QString& url)
{
    qDebug() << "OpenUrl - 打开URL:" << url;
    
    if (url.isEmpty()) {
        qDebug() << "OpenUrl - URL为空，无法打开";
        return;
    }
    
    QUrl qurl(url);
    
    bool success = QDesktopServices::openUrl(qurl);
    if (success) {
        qDebug() << "OpenUrl - 成功打开URL:" << url;
    } else {
        qDebug() << "OpenUrl - 打开URL失败:" << url;
    }
}

void PrescriptionChecker::onNetworkReplyFinished()
{
    if (!m_currentReply) {
        return;
    }
    
    int problem = -1;
    QString presId;
    QString random;
    QString message;
    QJsonObject response;
    
    if (m_currentReply->error() == QNetworkReply::NoError) {
        QByteArray data = m_currentReply->readAll();
        qDebug() << "收到响应:" << data;
        
        if (parseResponse(data, problem, presId, random)) {
            qDebug() << "解析响应成功 - hasProblem:" << problem << "presId:" << presId << "random:" << random;
        } else {
            qDebug() << "解析响应失败";
        }
    } else {
        qDebug() << "网络请求失败:" << m_currentReply->errorString();
    }

    // 如果hasProblem为1，显示Web页面
    if (problem == 1) {
        showWebPageDialog(QString("%1?presId=%2&random=%3").arg(m_webPageUrl).arg(presId).arg(random));
    }
    else {
        DoctorCheck(2, m_xmlData);
        m_dataCallback("0");
    }
    
    // 清理
    m_currentReply->deleteLater();
    m_currentReply = nullptr;
}

bool PrescriptionChecker::parseResponse(const QByteArray& data, int& problem, QString& presId, QString& random)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    
    if (error.error != QJsonParseError::NoError) {
        qDebug() << "JSON解析错误:" << error.errorString();
        return false;
    }
    
    if (!doc.isObject()) {
        qDebug() << "响应不是有效的JSON对象";
        return false;
    }
    
    QJsonObject dataObj = doc.object()["data"].toObject();
    
    // 检查是否有hasProblem字段
    if (dataObj.contains("hasProblem")) {
        problem = dataObj["hasProblem"].toInt();
    } else {
        return false;
    }
    
    if (dataObj.contains("presId")) {
        presId = dataObj["presId"].toString();
    } else {
        return false;
    }
    
    // 生成随机数（位数没有要求）
    random = QString::number(QRandomGenerator::global()->generate());
    
    return true;
}

void PrescriptionChecker::showWebPageDialog(const QString& url)
{
    // 如果已有对话框，先关闭它
    if (m_currentDialog) {
        m_currentDialog->close();
        m_currentDialog->deleteLater();
    }
    
    // 创建一个对话框来显示Web页面
    QDialog* dialog = new QDialog();
    m_currentDialog = dialog;  // 保存对话框引用
    dialog->setWindowTitle("处方检查结果 - 合理用药实时审核");
    dialog->setModal(true);
    dialog->resize(m_dialogWidth, m_dialogHeight);
    
    qDebug() << "显示弹窗 - 宽度:" << m_dialogWidth << "高度:" << m_dialogHeight;
    
    QVBoxLayout* layout = new QVBoxLayout(dialog);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    
    // 创建Web视图
    QWebEngineView* webView = new QWebEngineView(dialog);
    layout->addWidget(webView);
    
    // 设置WebView属性
    webView->setAttribute(Qt::WA_DeleteOnClose, false);
    
    // 加载URL
    QUrl targetUrl(url);
    
    // 设置用户代理，模拟浏览器
    webView->page()->profile()->setHttpUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
    
    // 设置WebChannel，将Qt对象暴露给JavaScript
    m_webChannel->registerObject("qtObject", this);
    webView->page()->setWebChannel(m_webChannel);
    
    webView->load(targetUrl);
    
    // 设置对话框属性
    dialog->setAttribute(Qt::WA_DeleteOnClose, true);
    
    // 当对话框关闭时清理WebView
    connect(dialog, &QDialog::finished, [webView]() {
        if (webView) {
            webView->stop();
            webView->setPage(nullptr);
        }
    });
    
    // 显示对话框
    dialog->show();
}
